<template>
  <el-dialog v-model="visible" :title="form._id ? '编辑' : '添加'" width="550px" @closed="onReset">
    <el-form :model="form" label-width="85px" :rules="rules" ref="formRef">
      <el-form-item label="店铺名称" prop="shopName">
        <el-input v-model="form.shopName" placeholder="请输入店铺名称" clearable />
      </el-form-item>
      <el-form-item label="店铺ID" prop="shopId">
        <el-input v-model="form.shopId" placeholder="请输入店铺ID" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from 'vue';
import type { FormInstance } from 'element-plus';
import type { IRoleItem } from '@/api/role/type';
import { updateRoleApi } from '@/api/role';
import { addShopWhiteListApi } from "@/api/auth";

import { ElMessage } from 'element-plus';

const rules = {
  shopName: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
  shopId: [{ required: true, message: '请输入店铺ID', trigger: 'blur' }]
};
const visible = ref(false);
const formRef = ref<FormInstance>();
interface UseForm {
  [key: string]: string;
}
const form = reactive<UseForm>({
  _id: '',
  shopName: '',
  shopId: ''
});

const init = async (data?: IRoleItem) => {
  visible.value = true;
  if (data) {
    await nextTick();
    Object.assign(form, data);
  }
};
const onReset = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  for (let key in form) {
    form[key] = '';
  }
};

const onSubmit = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      console.log('提交新增用户');
      if (!form._id) {
        await addShopWhiteListApi(form);
        ElMessage.success('添加成功');
        visible.value = false;
        onReset();
        props.getList();
      } else {
        // 编辑
        await updateRoleApi(form);
        ElMessage.success('编辑成功');
        visible.value = false;
        onReset();
        props.getList();
      }
    }
  });
};
const props = defineProps<{
  getList: Function;
}>();
defineExpose({ init });
</script>

<style lang="scss" scoped></style>
